package com.aboverock.core.spring;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author Rock Wang
 */
@Component
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    private static final Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
    private static ApplicationContext applicationContext = null;

    public SpringContextHolder() {
    }

    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBean(name, clazz);
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    public static Object getBean(String name) {
        assertContextInjected();
        return applicationContext.getBean(name);
    }

    public static void clearHolder() {
        logger.debug("清除SpringContextHolder中的ApplicationContext:{}", applicationContext);
        applicationContext = null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
        if (SpringContextHolder.applicationContext != null) {
            logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:{}", SpringContextHolder.applicationContext);
        }

        SpringContextHolder.applicationContext = applicationContext;
    }

    @Override
    public void destroy() throws Exception {
        clearHolder();
    }

    private static void assertContextInjected() {
        if (applicationContext == null) {
            logger.warn("applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
        }

    }

    public static String getActiveProfile() {
        return ArrayUtils.isEmpty(applicationContext.getEnvironment().getActiveProfiles()) ? null : applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    public static boolean isProduction() {
        return "prod".equalsIgnoreCase(getActiveProfile());
    }
}

